package com.yupi.springbootinit.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yupi.springbootinit.mapper.OutboxEventMapper;
import com.yupi.springbootinit.model.entity.OutboxEvent;
import com.yupi.springbootinit.service.OutboxService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.UUID;

@Service
@Slf4j
public class OutboxServiceImpl implements OutboxService {

    @Resource
    private OutboxEventMapper outboxEventMapper;

    @Resource
    private ObjectMapper objectMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void enqueue(String eventId, String eventType, String routingKey, Object payload) {
        try {
            OutboxEvent e = new OutboxEvent();
            e.setEventId(eventId != null ? eventId : UUID.randomUUID().toString());
            e.setEventType(eventType);
            e.setRoutingKey(routingKey);
            e.setPayload(objectMapper.writeValueAsString(payload));
            e.setStatus("PENDING");
            e.setRetryCount(0);
            Date now = new Date();
            e.setCreatedAt(now);
            e.setUpdatedAt(now);
            outboxEventMapper.insert(e);
            log.debug("Enqueued outbox event: {}, rk={}", e.getEventId(), routingKey);
        } catch (Exception ex) {
            log.error("Enqueue outbox failed, rk={}", routingKey, ex);
            throw new RuntimeException("enqueue outbox failed", ex);
        }
    }
}